package com.yami.shop.distribution.api.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.distribution.UserShoppingDataDto;
import com.yami.shop.bean.model.User;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.IdUtil;
import com.yami.shop.common.util.Json;
import com.yami.shop.dao.OrderMapper;
import com.yami.shop.distribution.api.param.DistributionUserParam;
import com.yami.shop.distribution.common.constants.DistributionUserStateEnum;
import com.yami.shop.distribution.common.model.DistributionUser;
import com.yami.shop.distribution.common.service.DistributionUserService;
import com.yami.shop.distribution.common.vo.DistributionConfigVO;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.SysConfigService;
import com.yami.shop.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author yami
 */
@Slf4j
@RestController
@RequestMapping("/p/distribution/register")
@Tag(name = "分销员注册接口")
public class DistributionRegisterController {

    @Autowired
    private DistributionUserService distributionUserService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private IdUtil idUtil;
    @Autowired
    private UserService userService;

    @GetMapping("/condition")
    @Operation(summary =  "成为分销员所需要填写的信息")
    public ServerResponseEntity<DistributionConfigVO> getDistributionAuditingInfoVO() {
        DistributionConfigVO distributionConfigVO = sysConfigService.getSysConfigObject(Constant.DISTRIBUTION_CONFIG, DistributionConfigVO.class);
//        DistributionAuditingInfoVO distributionAuditingInfoVO = new DistributionAuditingInfoVO();
//        distributionAuditingInfoVO.setIdentityCardNumber(distributionConfigVO.getIdentityCardNumber());
//        distributionAuditingInfoVO.setRealName(distributionConfigVO.getRealName());
//        distributionAuditingInfoVO.setIdentityCardPic(distributionConfigVO.getIdentityCardPic());
        return ServerResponseEntity.success(distributionConfigVO);
    }

    @PostMapping("/addDistributionUser")
    @Operation(summary =  "申请成为分销员", description = "申请成为分销员，返回分销员状态 0 待审核 1 正常")
    public ServerResponseEntity<Integer> addDistributionUser(@Valid @RequestBody DistributionUserParam distributionUserParam) {
        log.debug(Json.toJsonString(distributionUserParam));
        Long shopId = Constant.PLATFORM_SHOP_ID;
        // 店铺分销员审核设置
        DistributionConfigVO distributionConfigVO = sysConfigService.getSysConfigObject(Constant.DISTRIBUTION_CONFIG, DistributionConfigVO.class);
        // 判断传入的资料是否齐全
        if (distributionConfigVO == null) {
            // 分销设置异常
            throw new YamiShopBindException("yami.distribution.set.exception");
        }

        if (distributionConfigVO.getIdentityCardNumber()) {
            if (!StrUtil.isNotBlank(distributionUserParam.getIdentityCardNumber())) {
                // 申请填写信息不全,需要身份证号
                throw new YamiShopBindException("yami.distribution.info.cardno");
            }
        }
        if (distributionConfigVO.getIdentityCardPic()) {
            if (!StrUtil.isNotBlank(distributionUserParam.getIdentityCardPicBack()) || !StrUtil.isNotBlank(distributionUserParam.getIdentityCardPicFront()) || !StrUtil.isNotBlank(distributionUserParam.getIdentityCardPicHold())) {
                // 申请填写信息不全,需要身份证照片
                throw new YamiShopBindException("yami.distribution.info.pic");
            }
        }
        if (distributionConfigVO.getRealName()) {
            if (!StrUtil.isNotBlank(distributionUserParam.getRealName())) {
                // 申请填写信息不全,需要真实姓名
                throw new YamiShopBindException("yami.distribution.info.name");
            }
        }
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getUserByUserId(userId);
        DistributionUser distributionUser = distributionUserService.getByUserIdAndShopId(userId, shopId);
        checkUserInfo(distributionUserParam, distributionUser);
        distributionUser = new DistributionUser();
        distributionUser.setUserId(userId);
        distributionUser.setShopId(shopId);
        // 设置分享人信息
        setSharer(distributionUserParam, shopId, userId, distributionUser);
        if (distributionConfigVO.getAutoCheck() == 1) {
            autoCheck(shopId, distributionConfigVO, userId, distributionUser);
        } else {
            // 待审核
            distributionUser.setState(0);
        }
        //设置信息
        distributionUser.setUserMobile(distributionUserParam.getUserMobile());
        distributionUser.setRealName(distributionUserParam.getRealName());
        distributionUser.setIdentityCardNumber(distributionUserParam.getIdentityCardNumber());
        distributionUser.setIdentityCardPicFront(distributionUserParam.getIdentityCardPicFront());
        distributionUser.setIdentityCardPicHold(distributionUserParam.getIdentityCardPicHold());
        distributionUser.setIdentityCardPicBack(distributionUserParam.getIdentityCardPicBack());
        // level从1开始
        distributionUser.setLevel(1);
        //设置用户信息字段
        distributionUser.setNickName(user.getNickName());
        distributionUser.setPic(user.getPic());

        // 设置用户卡号
        distributionUser.setCardNo(idUtil.nextShortId());
        distributionUserService.registerDistributionUser(distributionUser);
        // 清除缓存
        distributionUserService.removeCacheByUserIdAndShopId(distributionUser.getUserId(), distributionUser.getShopId());
        distributionUserService.removeCacheByCardNo(distributionUser.getCardNo());
        return ServerResponseEntity.success(distributionUser.getState());
    }

    private void setSharer(DistributionUserParam distributionUserParam, Long shopId, String userId, DistributionUser distributionUser) {
        if (StrUtil.isNotBlank(distributionUserParam.getSharerCardNo())) {
            DistributionUser parentUser = distributionUserService.getByCardNo(distributionUserParam.getSharerCardNo());
            if (parentUser == null) {
                // 无法获取邀请人信息
                throw new YamiShopBindException("yami.distribution.get.examine");
            }
            if (!Objects.equals(parentUser.getShopId(), shopId)) {
                // 邀请人店铺信息有误
                throw new YamiShopBindException("yami.distribution.shop.error");
            }
            if (Objects.equals(parentUser.getUserId(), userId)) {
                // 自己无法邀请自己
                throw new YamiShopBindException("yami.distribution.user.error");
            }
            if (!Objects.equals(parentUser.getState(), DistributionUserStateEnum.PER_BAN.getValue())
                    && !Objects.equals(parentUser.getState(), DistributionUserStateEnum.BAN.getValue())) {
                //上级不能是暂时封禁或永久封禁状态
                //设置上级id
                distributionUser.setParentId(parentUser.getDistributionUserId());
                //设置上级ids
                if (parentUser.getParentId() == null) {
                    distributionUser.setParentIds(StringUtils.join(StrUtil.COMMA, parentUser.getDistributionUserId(), StrUtil.COMMA));
                } else {
                    distributionUser.setParentIds(StringUtils.join(parentUser.getParentIds(), parentUser.getDistributionUserId(), StrUtil.COMMA));
                }

                distributionUser.setGrade(parentUser.getGrade() + 1);
            }
        } else {
            distributionUser.setGrade(0);
        }
    }

    private void checkUserInfo(DistributionUserParam distributionUserParam, DistributionUser distributionUser) {
        if (distributionUser != null) {
            if (distributionUser.getState() == DistributionUserStateEnum.WAIT_AUDIT.getValue()) {
                // 你已经提交过审核了,请耐心等待
                throw new YamiShopBindException("yami.distribution.submit.examine");
            } else if (distributionUser.getState() == DistributionUserStateEnum.PER_BAN.getValue()) {
                // 该账户已被永久封禁
                throw new YamiShopBindException("yami.distribution.ban.examine");
            } else if (distributionUser.getState() == DistributionUserStateEnum.BAN.getValue()) {
//                // 已暂时封禁不可申请,请联系管理员
                throw new YamiShopBindException("yami.distribution.clear.examine");
            } else if (distributionUser.getState() == DistributionUserStateEnum.NORMAL.getValue()) {
                // 你的审核已经通过,无需再次审核
                throw new YamiShopBindException("yami.distribution.success.examine");
            }
        }
        List<DistributionUser> distributionUsersDb = distributionUserService.getDistributionUserByIdCardNumberAndUserMobile(distributionUserParam.getIdentityCardNumber(), distributionUserParam.getUserMobile());
        for (DistributionUser distributionUserDb : distributionUsersDb) {
            if (StrUtil.isNotBlank(distributionUserParam.getIdentityCardNumber()) && StrUtil.equals(distributionUserDb.getIdentityCardNumber(), distributionUserParam.getIdentityCardNumber())) {
                //该身份证号码已存在
                throw new YamiShopBindException("yami.id.number.already.exists");
            } else if (Objects.equals(distributionUserDb.getUserMobile(), distributionUserParam.getUserMobile())) {
                //该手机号码已存在
                throw new YamiShopBindException("yami.phone.number.already.exists");
            }
        }
        DistributionUser one = distributionUserService.getOne(new LambdaQueryWrapper<DistributionUser>().eq(DistributionUser::getUserMobile, distributionUserParam.getUserMobile())
                .and(item -> item.eq(DistributionUser::getState, DistributionUserStateEnum.BAN.getValue())
                        .or().eq(DistributionUser::getState, DistributionUserStateEnum.PER_BAN.getValue())));
        if (Objects.nonNull(one)){
            //该手机号码已存在
            throw new YamiShopBindException("yami.phone.number.already.exists");
        }

    }

    private void autoCheck(Long shopId, DistributionConfigVO distributionAuditingSet, String userId, DistributionUser distributionUser) {
        //判断是否需要购买置指定商品
        if (CollectionUtil.isNotEmpty(distributionAuditingSet.getProdIdList())) {
            boolean has = false;
            for (Long prodId : distributionAuditingSet.getProdIdList()) {
                // 判断有没有没有购买过指定商品
                if (orderMapper.hasBuySuccessProd(prodId, distributionUser.getUserId()) > 0) {
                    has = true;
                    break;
                }
            }
            if (!has) {
                // 不符合申请条件，请联系客服进行申请
                throw new YamiShopBindException("yami.distribution.user.Unqualified");
            }
        }
        UserShoppingDataDto userShoppingDataDto = orderMapper.calculateUserInShopData(shopId, userId);
        //判断是否需要消费金额条件
        if (distributionAuditingSet.getExpenseAmount() != null) {
            if (userShoppingDataDto.getSumOfConsumption() == null) {
                userShoppingDataDto.setSumOfConsumption(0.0);
            }
            if (userShoppingDataDto.getSumOfConsumption() < distributionAuditingSet.getExpenseAmount()) {
                // 消费金额不符合要求
                throw new YamiShopBindException("yami.distribution.fee.error");
            }
        }
        //判断是否需要达到消费笔数条件
        if (distributionAuditingSet.getExpenseNumber() != null) {
            if (userShoppingDataDto.getExpenseNumber() < distributionAuditingSet.getExpenseNumber()) {
                // 消费笔数不符合要求
                throw new YamiShopBindException("yami.distribution.fee.num");
            }
        }
        distributionUser.setState(1);
        distributionUser.setBindTime(new Date());
    }
}
